<template>
  <div class="departments">
    <el-card>
      <template #header>
        <span>组织结构</span>
      </template>
      <div class="tree">
        <!-- 标题栏 -->
        <TreeItem :item="topInfo" class="title"></TreeItem>
        <!-- 内容栏 -->
        <el-tree :data="list">
          <template v-slot="{ data }">
            <TreeItem
              style="width:100%"
              :item="data"
              @getData="getData"
            ></TreeItem>
          </template>
        </el-tree>
      </div>
    </el-card>
    <!-- 弹框组件 -->
    <DialogItem :initList="initList" @getData="getData"></DialogItem>
  </div>
</template>

<script>
import TreeItem from './components/TreeItem.vue'
import DialogItem from './components/dialogItem.vue'
import { companyDepartment } from '@/api/departaments.js'
export default {
  components: { TreeItem, DialogItem },
  data () {
    return {
      topInfo: { name: '传至', manager: '负责人', isShow: true, id: '' },
      list: [], // 树型组织架构数据
      initList: [] // 原始组织架构数据
    }
  },
  created () {
    this.getData()
  },
  methods: {
    // 获取企业的部门列表数据
    async getData () {
      const res = await companyDepartment()
      this.topInfo.name = res.data.companyName
      this.list = this.changeData(res.data.depts, '')
      this.initList = res.data.depts // 储存原始数据列表
      console.log('原始数据列表', res.data.depts)
      // console.log('组织架构', this.list)
    },
    // 将数据转换成树形数据结构
    changeData (arr, str = '') {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 30px;
  .tree {
    padding: 30px 60px;
    .title {
      margin-bottom: 15px;
      border-bottom: 1px solid #000;
    }
  }
}
</style>
